package utils

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"path/filepath"
	"strconv"
	"strings"
)

func FilterFile(dir string) []string{
	files,_:=filepath.Glob(dir + "/*.proto")
	return files
}

func CheckErr(err error){
	if err !=nil{
		panic(err)
	}
}

func ParseProto(proto string) []ProtocolInfo{
	content,err:=ioutil.ReadFile(proto)
	CheckErr(err)

	buffer := bytes.NewBuffer(content)
	infos:=make([]ProtocolInfo,0)
	lineCount:=0
	protocolStartIndex:= -1

	for{
		line,err:=buffer.ReadString('\n')
		if err !=nil{
			break
		}
		lineCount++

		if lineCount == 1{
			if !strings.Contains(line,"@protocol_id_start"){
				fmt.Printf("文件 %s 第一行未定义@protocol_id_start 跳过生成!\n",proto)
				break
			}
			protocolStartIndex = parseHead(line)
			continue
		}


		idx := strings.Index(line,"message")
		if idx <0 {
			continue
		}

		info:=ProtocolInfo{}
		info.ProtocolName = line[idx+7:]
		idx = strings.Index(info.ProtocolName,"{")
		if idx >=0{
			info.ProtocolName = info.ProtocolName[:idx]
		}
		info.ProtocolName = strings.Replace(info.ProtocolName,"\r","",-1)
		info.ProtocolName = strings.Replace(info.ProtocolName,"\n","",-1)
		info.ProtocolName = strings.Replace(info.ProtocolName," ","",-1)

		if len(info.ProtocolName) ==0{
			continue
		}

		protocolStartIndex ++
		info.ProtocolID  = protocolStartIndex

		infos = append(infos,info)
	}
	return infos
}

func parseHead(line string) int{
	bret:=strings.Contains(line,"@protocol_id_start")
	if bret == false{
		return -1
	}

	idx:=strings.LastIndex(line,"=")
	sub := line[idx+1:]
	sub = strings.Replace(sub," ","",-1)
	sub = strings.Replace(sub,"\r","",-1)
	sub = strings.Replace(sub,"\n","",-1)
	startIndex,err:=strconv.Atoi(sub)
	CheckErr(err)
	return startIndex
}